import React, {memo, useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";

import Header from "../../../components/main-header/Header";
import "./experiment.css";
import {saveExperimentCount, saveExperimentInfo, saveReagentsType} from "./store/actionCreators";
import {EXPERIMENT_MESSAGES, EXPERIMENT_MESSAGES_CN} from "./config";
import {saveData} from "../store/actionCreators";
import {STAGES_TYPE} from "../protocol/config";
import {saveExportObj, saveExportObjCn} from "../export/store/actionCreators";
import {deepClone} from "../../../common/utils";
import {translateStausInfoCE, translateStausInfoEC} from "../run/config";

export default memo(function Experiment() {
  const dispatch = useDispatch();
  const {userInfo, runStart, reagentsType, experimentInfo, data, exportObj, exportObjCn, isCN} = useSelector(state => ({
    userInfo: state.loginReducer.info,
    reagentsType: state.experimentReducer.reagentsType,
    experimentInfo: state.experimentReducer.experimentInfo,
    data: state.dataReducer.data,
    runStart: state.runReducer.runStart,
    exportObj: state.exportReducer.exportObj,
    exportObjCn: state.exportReducer.exportObjCn,
    isCN: state.languageReducer.isCN
  }));
  const experimentIdentifyTitle = ["Quantitation/Standard Curve", "Quantitation/Relative Standard Curve", "Quantitation/Comparative Cq (△△Cq)", "Melt Curve", "Genotyping", "Presence/Absence"];
  const experimentIdentifyTitle_CN = ["绝对定量/标准曲线", "相对定量/双标准曲线", "相对定量（∆∆Cq）", "熔解曲线", "基因分型", "阳性/阴性"];
  const experimentIdentifyTitleTrans = isCN ? experimentIdentifyTitle_CN : experimentIdentifyTitle;
  const reagentsTypeTitle = ["Probe", "SYBR Green"];
  const reagentsTypeTitle_CN = ["探针法", "染料法"];
  const reagentsTypeTitleTrans = isCN ? reagentsTypeTitle_CN : reagentsTypeTitle;
  const runModeTitle = ["Fast/Block Temperature", "Standard/Sample Temperature"];
  const runModeTitle_CN = ["快速/模块控温", "标准/样本控温"];
  const runModeTitleTrans = isCN ? runModeTitle_CN : runModeTitle;
  const [experimentIdentifyIndex, setIdentifyIndex] = useState(experimentIdentifyTitle.indexOf(experimentInfo.experimentIdentify));
  const [reagentsTypeIndex, setReagentsTypeIndex] = useState(reagentsType);
  const [runModeIndex, setRunModeIndex] = useState(runModeTitle.indexOf(experimentInfo.runMode));
  const [experimentIdentifyMessages, setExperimentIdentifyMessages] = useState(isCN ? EXPERIMENT_MESSAGES_CN.quantitationStandardCurve : EXPERIMENT_MESSAGES.quantitationStandardCurve);
  const [runModeMessages, setRunModeMessages] = useState(isCN ? EXPERIMENT_MESSAGES_CN.fastBlockTemperature : EXPERIMENT_MESSAGES.fastBlockTemperature);

  let cloneExportObj = {};

  useEffect(() => {
    //  初始化ExperimentIdentity
    let experimentIdentity = isCN ? translateStausInfoEC(data.experimentIdentity) : translateStausInfoCE(data.experimentIdentity);
    let experimentIdentityIndex = experimentIdentifyTitleTrans.findIndex(item => item === experimentIdentity);
    experimentIdentityIndex < 0 && (experimentIdentityIndex = 0);
    setIdentifyIndex(experimentIdentityIndex);
    switch (experimentIdentityIndex) {
      case 0:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationStandardCurve : EXPERIMENT_MESSAGES.quantitationStandardCurve);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[0]}));
        break;
      case 1:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationRelativeStandardCurve : EXPERIMENT_MESSAGES.quantitationRelativeStandardCurve);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[1]}));
        break;
      case 2:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationComparativeCq : EXPERIMENT_MESSAGES.quantitationComparativeCq);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[2]}));
        break;
      case 3:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.meltCurve : EXPERIMENT_MESSAGES.meltCurve);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[3]}));
        break;
      case 4:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.genotyping : EXPERIMENT_MESSAGES.genotyping);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[4]}));
        break;
      case 5:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.presence : EXPERIMENT_MESSAGES.presence);
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[5]}));
        break;
    }
    // 初始化Reagents Type
    let reagentsType = isCN ? translateStausInfoEC(data.reagentsType) : translateStausInfoCE(data.reagentsType);
    let reagentsTypeIndex = reagentsTypeTitleTrans.findIndex(item => item === reagentsType);
    reagentsTypeIndex < 0 && (reagentsTypeIndex = 0);
    setReagentsTypeIndex(reagentsTypeIndex);
    switch (reagentsTypeIndex) {
      case 0:
        dispatch(saveData({...data, reagentsType: reagentsTypeTitleTrans[0], protocol: {...data.protocol, stages: [STAGES_TYPE.hold, STAGES_TYPE.amplificationCycle]}}));
        break;
      case 1:
        dispatch(saveData({...data, reagentsType: reagentsTypeTitleTrans[1], protocol: {...data.protocol, stages: [STAGES_TYPE.hold, STAGES_TYPE.amplificationCycle, STAGES_TYPE.melt]}}));
        break;
    }
    // 初始化RunMode
    let RunModeIndex = 0;
    if (data.runModeIsSample) {
      RunModeIndex = 1;
    }
    setRunModeIndex(RunModeIndex);
    switch (RunModeIndex) {
      case 0:
        setRunModeMessages(isCN ? EXPERIMENT_MESSAGES_CN.fastBlockTemperature : EXPERIMENT_MESSAGES.fastBlockTemperature);
        dispatch(saveData({...data, runModeIsSample: false}));
        break;
      case 1:
        setRunModeMessages(isCN ? EXPERIMENT_MESSAGES_CN.standardSampleTemperature : EXPERIMENT_MESSAGES.standardSampleTemperature);
        dispatch(saveData({...data, runModeIsSample: true}));
        break;
    }
  }, []);

  function experimentIdentifyClick(item, indey) {
    cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
    setIdentifyIndex(indey);
    switch (indey) {
      case 0:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationStandardCurve : EXPERIMENT_MESSAGES.quantitationStandardCurve);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[0];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[0]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 1:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationRelativeStandardCurve : EXPERIMENT_MESSAGES.quantitationRelativeStandardCurve);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[1];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[1]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 2:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.quantitationComparativeCq : EXPERIMENT_MESSAGES.quantitationComparativeCq);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[2];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[2]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 3:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.meltCurve : EXPERIMENT_MESSAGES.meltCurve);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[3];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[3]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 4:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.genotyping : EXPERIMENT_MESSAGES.genotyping);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[4];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[4]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 5:
        setExperimentIdentifyMessages(isCN ? EXPERIMENT_MESSAGES_CN.presence : EXPERIMENT_MESSAGES.presence);
        cloneExportObj.experiment.experimentSetting.experimentIdentify = experimentIdentifyTitleTrans[5];
        dispatch(saveData({...data, experimentIdentity: experimentIdentifyTitleTrans[5]}));
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      default:
        setExperimentIdentifyMessages("error");
    }
    dispatch(saveExperimentInfo({...experimentInfo, experimentIdentify: experimentIdentifyTitleTrans[indey]}));
  }

  function reagentsTypeClick(item, indey) {
    if (indey === 1 && experimentIdentifyMessages === EXPERIMENT_MESSAGES.presence) {
      return;
    }
    cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
    setReagentsTypeIndex(indey);
    dispatch(saveReagentsType(indey, true));
    switch (indey) {
      case 0:
        dispatch(saveData({...data, reagentsType: reagentsTypeTitleTrans[0], protocol: {...data.protocol, stages: [STAGES_TYPE.hold, STAGES_TYPE.amplificationCycle]}}));
        cloneExportObj.experiment.experimentSetting.reagentsType = reagentsTypeTitleTrans[0];
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 1:
        dispatch(saveData({...data, reagentsType: reagentsTypeTitleTrans[1], protocol: {...data.protocol, stages: [STAGES_TYPE.hold, STAGES_TYPE.amplificationCycle, STAGES_TYPE.melt]}}));
        cloneExportObj.experiment.experimentSetting.reagentsType = reagentsTypeTitleTrans[1];
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
    }
    dispatch(saveExperimentInfo({...experimentInfo, reagentsType: item}));
  }

  function runModeClick(item, indey) {
    cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
    setRunModeIndex(indey);
    switch (indey) {
      case 0:
        setRunModeMessages(isCN ? EXPERIMENT_MESSAGES_CN.fastBlockTemperature : EXPERIMENT_MESSAGES.fastBlockTemperature);
        dispatch(saveData({...data, runModeIsSample: false}));
        cloneExportObj.experiment.experimentSetting.runMode = runModeTitleTrans[0];
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      case 1:
        setRunModeMessages(isCN ? EXPERIMENT_MESSAGES_CN.standardSampleTemperature : EXPERIMENT_MESSAGES.standardSampleTemperature);
        dispatch(saveData({...data, runModeIsSample: true}));
        cloneExportObj.experiment.experimentSetting.runMode = runModeTitleTrans[0];
        isCN ? dispatch(saveExportObjCn(cloneExportObj))
          : dispatch(saveExportObj(cloneExportObj));
        break;
      default:
        setRunModeMessages("error");
    }
    dispatch(saveExperimentInfo({...experimentInfo, runMode: runModeTitleTrans[indey]}));
  }

  return (
    <div>
      <Header name={isCN ? "实验设置" : "Experiment"} imgPosition="0px"/>
      <section className="mainSection experimentPage">
        <div style={{margin: "10px auto"}}>
          <div/>
          <div>{isCN ? "实验属性" : "Experiment Properties"}</div>
        </div>
        <div>
          <header className="componentTitle" style={{width: "300px"}}>{isCN ? "实验信息" : "Experiment Information"}</header>
          <div className="experimentPagePart0">
            <div>
              <div>
                <div>{isCN ? "实验名称" : "Experiment Name"}</div>
                <p/>
                <input type="text" defaultValue={data.experimentName}
                       readOnly={runStart}
                       onBlur={e => dispatch(saveData({...data, experimentName: e.target.value}))}
                       onKeyUp={e => e.target.value = e.target.value.replace(/[\u0391-\uFFE5`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\+={}|《》？：“”【】、；‘'，。、]/gi, '')}
                />
              </div>
              <div>
                <div>{isCN ? "条形码" : "Barcode"}</div>
                <input type="text" defaultValue={data.barcode}
                       onBlur={e => dispatch(saveData({...data, barcode: e.target.value}))}
                />
              </div>
              <div>
                <div>{isCN ? "用户" : "User Name"}</div>
                <input type="text" readOnly={true} defaultValue={userInfo.username}
                       onKeyUp={e => e.target.value = e.target.value.replace(/[\u0391-\uFFE5]/gi, '')}
                />
              </div>
            </div>
            <div>
              <div>{isCN ? "实验描述" : "Comments:"}</div>
              <textarea defaultValue={data.comments}
                        onBlur={e => dispatch(saveData({...data, comments: e.target.value}))}
              />
            </div>
          </div>
        </div>
        <div>
          <header className="componentTitle" style={{width: "300px"}}>{isCN ? "实验类型" : "Experiment Identity"}</header>
          <div className="experimentPagePart1">
            <ul>
              {
                experimentIdentifyTitleTrans.map((item, index) => (
                  <li key={item}
                      className={experimentIdentifyIndex === index ? "experimentPageActive" : ""}
                      onClick={() => experimentIdentifyClick(item, index)}
                  >{item}</li>
                ))
              }
            </ul>
            <div>{experimentIdentifyMessages}</div>
          </div>
        </div>
        <div>
          <header className="componentTitle" style={{width: "300px"}}>{isCN ? "试剂类型" : "Reagents Type"}</header>
          <div className="experimentPagePart2">
            <ul>
              {
                reagentsTypeTitleTrans.map((item, index) => (
                  <li key={item}
                      style={index === 1 && experimentIdentifyMessages === EXPERIMENT_MESSAGES.presence ? {backgroundColor: "#ccc"} : null}
                      className={reagentsTypeIndex === index ? "experimentPageActive" : ""}
                      onClick={() => reagentsTypeClick(item, index)}
                  >{item}</li>
                ))
              }
            </ul>
          </div>
        </div>
        <div>
          <header className="componentTitle" style={{width: "300px"}}>{isCN ? "运行模式" : "Run Mode"}</header>
          <div className="experimentPagePart3">
            <ul>
              {
                runModeTitleTrans.map((item, index) => (
                  <li key={item}
                      className={runModeIndex === index ? "experimentPageActive" : ""}
                      onClick={() => runModeClick(item, index)}
                  >{item}</li>
                ))
              }
            </ul>
            <div>{runModeMessages}</div>
          </div>
        </div>
      </section>
    </div>
  );
});